import * as express from "express";
import tools from '../tools/upload'
import Sql from '../mysqlOption/Sql'
import { MyCURD } from "../my/CURDMySQL";
import dayjs from "dayjs";
import uuid from "node-uuid";
import fs from 'fs'
import path from 'path'
const router = express.Router();
const time = dayjs().format("YYYY_MM_DD")
router.post("/api/uploadlunbotu", tools.multerFun(time, 'lunbotu').single("lunbotu"), (req, res) => {
    // 上传轮播图的接口
    const sql_insert_lunbotu = 'insert into lunbotu(iconlocation,code,local) values(?,?,?);'
    const iconlocation = "http://localhost:3000/uploadfile/lunbotu/" + `${time}/` + req.file?.filename;
    const code: string = req.body.code;
    const local: string = req.file!.path;
    Sql.query(sql_insert_lunbotu, [iconlocation, code, local], (err, result) => {
        if (err) {
            console.log("写入数据库出错")
            console.log(err);
            return err.message;
        } else {
            res.send({
                success: "上传成功",
                locat: "http://localhost:3000/uploadfile/lunbotu/" + `${time}/` + req.file?.filename
            })
        }
    })
})

router.post("/api/uploadicon", tools.multerFun(time, 'icon').single("icon"), (req, res) => {
    // 上传miniIcon的接口
    const sql_insert_miniIcon: string = "insert into icon(iconlocation,code,local,title) values(?,?,?,?)";
    const iconlocation: string = "http://localhost:3000/uploadfile/icon/" + `${time}/` + req.file?.filename;
    const code: string = req.body.code;
    const local: string = req.file!.path;
    const title: string = req.body.title;
    Sql.query(sql_insert_miniIcon, [iconlocation, code, local, title], (err, result) => {
        if (err) {
            console.log(err);
            res.send({
                msg: "写入数据库出错",
                code: 400
            })
            return err;
        }
        res.send({
            msg: "写入成功",
            code: 200,
            fileLink: iconlocation
        })
    })
})

router.post("/api/uploadminiswiper", tools.multerFun(time, "miniswiper").single("miniswiper"), (req, res) => {
    // 上传miniswiper的接口
    const sql_insert_miniSwiper: string = 'insert into miniswiper(iconlocation,code,local) values(?,?,?)';
    const iconlocation: string = "http://localhost:3000/uploadfile/miniswiper/" + `${time}/` + req.file?.filename;
    const code: string = req.body.code;
    const local: string = req.file!.path;
    Sql.query(sql_insert_miniSwiper, [iconlocation, code, local], (err, result) => {
        if (err) {
            console.log(err)
            return res.send({
                msg: "上传miniswiper失败",
                code: 400
            })
        }
        res.send({
            msg: "上传miniswiper成功",
            code: 200,
            fileLink: iconlocation
        })
    })
})
interface Product {
    name: string; //商品的名称
    nowPrice: string; //现价
    afterPrice: string;//折后价
    describe: string; //商品的描述
    netPhoto: string[], //图片的网络位置
    localPhoto: string[], //图片的本地位置
}
// 单个文件的上传并且需要返回ID
router.post("/api/upload/productcreate", tools.multerFun(time, "product").single("productsingle"), (req, res) => {
    // 商品上传的接口
    // 接口需要接收4个数据  name nowprice afterprice describe(描述) 
    const insert = "insert into productinfo(productid,name,productdescribe,nowprice,beforeprice,picture,picturelocal) values(?,?,?,?,?,?,?)";
    const productid = uuid.v1();
    const picture = 'http://localhost:3000/uploadfile/product/' + `${time}/` + req.file?.filename;;
    const picturelocal = req.file?.path;
    const { name, nowprice, beforeprice, productdescribe } = req.body;
    Sql.query(insert, [productid, name, productdescribe, nowprice, beforeprice, picture, picturelocal], (err, result) => {
        if (err) {
            console.log(err)
            return res.send({
                msg: "写入数据库错误",
                linkerror: "/api/upload/productcreate",
                code: 400
            })
        }
        res.send({
            msg: "success",
            key: productid
        })
    })
})
// 上传多个文件使用array签名单个文件使用single
interface UploadArray {
    path: string,
    filename: string
}
router.post("/api/uploadproducts", tools.multerFun(time, "productdateils").array("product", 4), async (req, res) => {
    // 商品上传的接口
    // 接口需要接收4个数据  name nowprice afterprice describe(描述) 
    const Discard = req.files as UploadArray[];
    if (req.body.productID === '') {
        Discard.forEach((item) => {
            fs.unlink(item.path, (err) => {
                if (err) {
                    console.log(err);
                }
            })
        })
        return res.send({
            msg: "产品ID不能为空"
        })
    }
    const data = await MyCURD("select * from productinfo where productid = ? ", [req.body.productID]);
    if (data.length <= 0) {
        // 如果ID错误
        Discard.forEach((item) => {
            fs.unlink(item.path, (err) => {
                if (err) {
                    console.log(err);
                }
            })
        })
        return res.send({
            msg: "产品ID不存在"
        })
    }
    const temp_uploadData = req.files as UploadArray[];
    temp_uploadData.forEach(async (item) => {
        const temp_local = "http://localhost:3000/uploadfile/productdateils/" + `${time}/` + item.filename;
        await MyCURD("insert into productarray(product_id,picture_local,picture_net) values(?,?,?)", [req.body.productID, item.path, temp_local]);
    })
    res.send({
        msg: "写入详细内容成功"
    })

})
// 获取建单的情况的接口
router.get("/allproductID/:pageNum",async (req,res)=>{
    let page = req.params.pageNum;
    // select * from productinfo id > (?*5) limit 5
    const data = await MyCURD("select productid , name from productinfo where id >(?*5) limit 5 " ,[page])
    res.send({
        msg:"test",
        data
    })
})

export default router;